<template>
  <div class="container-box" style="height: calc(-114px + 100vh)">
    <div class="container-header">
      <div>
        <el-button @click="back" :icon="Back">返回</el-button>
      </div>
      <div>
        <el-button @click="preview">预览</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </div>
    </div>
    <DesignList v-model="formData" v-model:checkedColumn="checkedColumn" />
  </div>
</template>

<script setup lang="ts">
import DesignFormApi from "@/api/design/designForm";
import DesignListApi, { DesignListEdit } from "@/api/design/designList";
import { DesignListConfig, DesignListTableConfig, ListSetting } from "@/components/DesignList";
import successMsg from "@/utils/successMsg";
import { CloseBold, Back } from "@element-plus/icons-vue";

const type = ref<string>();
const route = useRoute(); //实例化路由
const id = route.params.id as string;
type.value = route.params.type as string;

const formData = ref<ListSetting>({
  fieldGroup: [],
  fieldCheckBox: [],
  fieldCheckAll: false,
  tableConfig: [],
  listConfig: {
    defaultOrderBy: 'CreateTime',
    defaultOrder: "descending"
  },
  menuConfig: {}
});

// 用于拖拽排序的列配置数组
const checkedColumn = ref<DesignListTableConfig[]>([]);
onMounted(async () => {
  // 根据ID获取数据
  if (type.value === 'update') {
    const data = await DesignListApi.details(id);
    Object.assign(formData.value, data);
    const fieldList = await DesignFormApi.queryFieldSelect(data.formId);
    formData.value.fieldCheckBox = fieldList;
    formData.value.tableConfig = JSON.parse(data.tableConfig || '[]') as DesignListTableConfig[];
    formData.value.fieldGroup = formData.value.tableConfig.map(x => x.fieldName);
    //设置全选按钮状态
    formData.value.fieldCheckAll = formData.value.fieldGroup.length === fieldList.length;
  }
})

const data = ref<DesignListEdit>({});
const submit = async () => {
  data.value.id = formData.value.id;
  data.value.name = formData.value.name;
  data.value.formId = formData.value.formId;
  data.value.formName = formData.value.formName;
  data.value.menuConfig = formData.value.menuConfig;
  data.value.tableConfig = JSON.stringify(checkedColumn.value);
  data.value.listConfig = formData.value.listConfig;
  const { success, message } = await DesignListApi[type.value](data.value);
  successMsg(success, message);
}

const openPreview = ref(false);
//预览
const preview = () => {
  openPreview.value = true;
}

const router = useRouter(); //实例化路由
//返回
const back = () => {
  router.push('/design/designlist');
}

</script>

<style lang="scss" scoped>
.container-box {
  box-sizing: border-box;
  background-color: white;
  display: flex;
  flex-direction: column;
  border: 1px solid var(--el-border-color);
}

.container-header {
  display: flex;
  border-bottom: 1px solid var(--el-border-color);
  padding: 10px;
  justify-content: space-between;
}

.container-content {
  height: 100%;
  display: flex;
  flex-direction: row;
}
</style>
